//
//  QRViewController.m
//  LCQRcodeScan
//
//  Created by 刘通超 on 16/6/30.
//  Copyright © 2016年 刘通超. All rights reserved.
//

#import "QRViewController.h"
#import "BookDetailViewController.h"
#import "MagazineDetailViewController.h"
#import "RegistViewController.h"
#import "CardLoginViewController.h"

/**
 *  屏幕 高 宽 边界
 */
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define SCREEN_BOUNDS  [UIScreen mainScreen].bounds

#define TOP (SCREEN_HEIGHT-220)/2
#define LEFT (SCREEN_WIDTH-220)/2

#define kScanRect CGRectMake(LEFT, TOP, 220, 220)

@interface QRViewController ()<AVCaptureMetadataOutputObjectsDelegate>{
    int num;
    BOOL upOrdown;
    NSTimer * timer;
    CAShapeLayer *cropLayer;
}
//导航条
@property (nonatomic, strong) UIImageView * navBar;
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;

@property (nonatomic, strong) UIImageView * line;

@end

@implementation QRViewController

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
    }
    return _navBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //导航条
    [self.view addSubview:self.navBar];
    
    //闪光灯开启/关闭
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[ImageNamed(@"light") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(lightButtonClicked:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    [self configView];
}

-(void)configView{
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:kScanRect];
    imageView.image = [UIImage imageNamed:@"pick_bg"];
    [self.view addSubview:imageView];
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(LEFT, TOP+10, 220, 2)];
    _line.image = [UIImage imageNamed:@"line.png"];
    [self.view addSubview:_line];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame), SCREEN_W, 35)];
    label.text = @"对准图书二维码进行扫描";
    label.textColor = COLOR_WHITE;
    label.font = FONTSIZE(17);
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];

}
-(void)viewWillAppear:(BOOL)animated{

    [self setCropRect:kScanRect];
    
    [self performSelector:@selector(setupCamera) withObject:nil afterDelay:0.3];

}

- (void)viewDidDisappear:(BOOL)animated{
    AVCaptureDevice *device = self.device;
    
    //修改前必须先锁定
    [self.device lockForConfiguration:nil];
    
    if (self.device.flashMode == AVCaptureFlashModeOn) {
        self.device.flashMode = AVCaptureFlashModeOff;
        self.device.torchMode = AVCaptureTorchModeOff;
    }
    [device unlockForConfiguration];
}

-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
        if (2*num == 200) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}


- (void)setCropRect:(CGRect)cropRect{
    cropLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, cropRect);
//    CGPathAddRect(path, nil, self.view.bounds);
    CGPathAddRect(path, nil, CGRectMake(0, 64, SCREEN_W, SCREEN_H - 64));
    
    [cropLayer setFillRule:kCAFillRuleEvenOdd];
    [cropLayer setPath:path];
    [cropLayer setFillColor:[UIColor blackColor].CGColor];
    [cropLayer setOpacity:0.6];
    
    
    [cropLayer setNeedsDisplay];
    
    [self.view.layer addSublayer:cropLayer];
}

- (void)setupCamera
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device==nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //设置扫描区域
    CGFloat top = TOP/SCREEN_HEIGHT;
    CGFloat left = LEFT/SCREEN_WIDTH;
    CGFloat width = 220/SCREEN_WIDTH;
    CGFloat height = 220/SCREEN_HEIGHT;
    ///top 与 left 互换  width 与 height 互换
    [_output setRectOfInterest:CGRectMake(top,left, height, width)];

   
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    [_output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode, nil]];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    // Start
    [_session startRunning];
}

//开启/关闭闪光灯
- (void)lightButtonClicked:(UIButton *)button{
    AVCaptureDevice *device = self.device;
    
    //修改前必须先锁定
    [self.device lockForConfiguration:nil];
    
    //必须判定是否有闪光灯，否则如果没有闪光灯会崩溃
    if ([self.device hasFlash]) {
        if (self.device.flashMode == AVCaptureFlashModeOff) {
            self.device.flashMode = AVCaptureFlashModeOn;
            self.device.torchMode = AVCaptureTorchModeOn;
        } else if (self.device.flashMode == AVCaptureFlashModeOn) {
            self.device.flashMode = AVCaptureFlashModeOff;
            self.device.torchMode = AVCaptureTorchModeOff;
        }
    } else {
        [ZRProgressHUD showMsgWithoutView:@"没有闪光灯"];
    }
    [device unlockForConfiguration];
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] > 0)
    {
        //停止扫描
        [_session stopRunning];
        [timer setFireDate:[NSDate distantFuture]];
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        DLog(@"扫描结果：%@", stringValue);

        
        NSArray *arry = metadataObject.corners;
        for (id temp in arry) {
            NSLog(@"%@",temp);
        }
        
        if ([stringValue containsString:@"t="] && [stringValue containsString:@"r="]) {
             NSString * r = [stringValue componentsSeparatedByString:@"&r="][1];
            // t = 1 书籍，t = 2 视频，t = 4 期刊
            if ([stringValue containsString:@"t=1"]) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否阅读这本书籍" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [_session startRunning];
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"阅读" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSDictionary *tempDic = @{@"id": r};

                    if (self.delegate) {
                        [self.navigationController popViewControllerAnimated:YES];
                        [self.delegate resultDetail:1 dataDic:tempDic];
                        
                    }
                    
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            } else if ([stringValue containsString:@"t=2"]) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否播放这段视频" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [_session startRunning];
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"播放" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSDictionary *tempDic = @{@"filePath": r};
                    if (self.delegate) {
                        [self.navigationController popViewControllerAnimated:YES];
                        [self.delegate resultDetail:2 dataDic:tempDic];
                    }
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            } else if ([stringValue containsString:@"t=4"]) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否阅读这本期刊" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [_session startRunning];
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"阅读" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSDictionary *tempDic = @{@"id": r};
                    if (self.delegate) {
                        [self.navigationController popViewControllerAnimated:YES];
                        [self.delegate resultDetail:4 dataDic:tempDic];
                    }
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            } else {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"不支持的二维码" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    if (_session != nil && timer != nil) {
                        [_session startRunning];
                        [timer setFireDate:[NSDate date]];
                    }
                    
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        } else if ([stringValue containsString:@"qrcode.jsp?u="]) {
            NSString *u = [[stringValue componentsSeparatedByString:@"u="][1] substringToIndex:10];
            DLog(@"卡号%@", u);
            
            NSString *rcpwd = [[stringValue componentsSeparatedByString:@"="] lastObject];
            DLog(@"卡密码%@", rcpwd);
            
            NSString *URL = [NSString stringWithFormat:KcardInfo, KHostAddress, u];
            [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
                if ([[responseObject objectForKey:@"error"] intValue] != 0) {
                    [ZRProgressHUD showMsgWithoutView:@"卡无效"];
                    [_session startRunning];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                    [self.delegate sacnCard:responseObject cardNumber:u cardPwd:rcpwd];
                }
                
            } failure:^(NSError *error) {
                DLog(@"%@", error);
                [_session startRunning];
            }];
            
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"不支持的二维码" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (_session != nil && timer != nil) {
                    [_session startRunning];
                    [timer setFireDate:[NSDate date]];
                }
                
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    } else {
        NSLog(@"无扫描信息");
        return;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
